package com.kyg.tjtoolmanager.controller;

import com.kyg.tjtoolmanager.App;
import com.kyg.tjtoolmanager.db.SQLObserver;
import com.kyg.tjtoolmanager.db.SQLReaderListener;
import com.kyg.tjtoolmanager.db.SQLiteUtils;
import com.kyg.tjtoolmanager.module.Reader;
import com.kyg.tjtoolmanager.net.netty.factory.ChannelFactory;
import com.kyg.tjtoolmanager.ui.StageUIHelper;
import com.kyg.tjtoolmanager.utils.Utils;
import io.netty.util.internal.StringUtil;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.util.Callback;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import java.util.function.Consumer;


public class SettingController extends BaseController implements SQLReaderListener {
    @FXML
    private TextField FieldHttpUrl;
    @FXML
    private TextField FieldLocalIP, FieldNettyPort;
    @FXML
    private TextField FieldFaceIP;
    @FXML
    private Label Label_faceStats;
    @FXML
    TableView<Reader> tbViewReaders;
    @FXML
    TableColumn<Reader, String> tbcReaderType, tbcConType, tbcAddress;
    private ObservableList<Reader> data = FXCollections.observableArrayList();

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        super.initialize(url, resourceBundle);
        FieldHttpUrl.setText(App.globalVal.httpHost);
        FieldLocalIP.setText(Utils.getLocalIP());
        FieldNettyPort.setText(App.globalVal.nettyPort);
        FieldFaceIP.setText(App.globalVal.faceIp);

        //判断人脸摄像头是否在线
        if (ChannelFactory.isExistIp(App.globalVal.faceIp)) {
            Label_faceStats.setText("在线");
            Label_faceStats.setTextFill(Color.GREEN);
        } else {
            Label_faceStats.setText("离线");
            Label_faceStats.setTextFill(Color.RED);
        }

        List<Reader> readerList = SQLiteUtils.getLocalAllReader();
        data.addAll(readerList);
        //获取本地读写器
        tbViewReaders.getItems().addAll(data);
//        tbViewReaders.setCellFactory(listViewReaders -> new ItemReader());
//        TableColumn<Reader,String> col_name = new TableColumn<>("类型");
//        tbViewReaders.getColumns().add(col_name);//添加到tableView中展示
        //设置该列的数据类型-返回单元格内容
        tbcReaderType.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Reader, String>, ObservableValue<String>>() {
            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<Reader, String> param) {
                SimpleStringProperty name = new SimpleStringProperty(param.getValue().getReaderType());
                return name;
            }
        });
        tbcConType.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Reader, String>, ObservableValue<String>>() {
            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<Reader, String> param) {
                SimpleStringProperty name = new SimpleStringProperty(param.getValue().getConnectType());
                return name;
            }
        });
        tbcAddress.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Reader, String>, ObservableValue<String>>() {
            @Override
            public ObservableValue<String> call(TableColumn.CellDataFeatures<Reader, String> param) {
                SimpleStringProperty name = new SimpleStringProperty(param.getValue().getAddress());
                return name;
            }
        });
        tbViewReaders.setRowFactory(readerTableView -> {
            TableRow<Reader> row = new TableRow<>();
            row.setOnMouseClicked(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent mouseEvent) {
                    if (mouseEvent.getClickCount() == 2 && !row.isEmpty()) {
                        Reader reader = row.getItem();
                        //保存全局变量
                        StageUIHelper.getInstance()
                                .setTitle("读写器设置")
                                .setFxml(ReaderEditController.FXMLFile)
                                .setPercent(0.3f)
                                .setSendData(reader)
                                .show();
                        SQLiteUtils.insertLog("tableview click " + reader.toString());
                    }
                }
            });
            return row;
        });
    }

    @Override
    public void onShow() {
        super.onShow();
        SQLiteUtils.insertLog("show setting");
        SQLObserver.addReaderChangeListener(this);
        double rootW = rootLayout.getWidth() - 40;
        double rootH = rootLayout.getHeight();
        tbViewReaders.setPrefWidth(rootW);
        tbViewReaders.setPrefHeight(rootH - 250);
        tbcReaderType.setPrefWidth(100);
        tbcAddress.setPrefWidth(100);
        tbcConType.setPrefWidth(rootW - tbcReaderType.getPrefWidth() - tbcAddress.getPrefWidth() - 2);
    }

    @Override
    public void onClose() {
        super.onClose();
        SQLObserver.removeReaderChangeListener(this);
    }

    public void reloadReader() {
        List<Reader> readerList = SQLiteUtils.getLocalAllReader();
        data.clear();
        data.addAll(readerList);
        //获取本地读写器
        tbViewReaders.getItems().clear();
        tbViewReaders.getItems().addAll(data);
    }

    @FXML
    protected void onAddReaderClick() {
        if (App.wareHouses.size() == 0) {
            StageUIHelper.getInstance().showTipAlert("库房信息为空，请在后台添加库房信息。\n重启本应用即可重新获取库房信息");
            return;
        }
        //添加读写器
        StageUIHelper.toCustomUI("读写器设置", ReaderEditController.FXMLFile, 0.3f, true);
    }

    @FXML
    protected void onLogClick() {
        //日志
        StageUIHelper.toCustomUI("日志", "log-view.fxml", 0.5f, true);
    }
    @FXML
    protected void onSettingClick() {
//        SpeechUtil.textToSpeech("欢迎使用");
        String url = FieldHttpUrl.getText().toString().trim();
        if (StringUtil.isNullOrEmpty(url)) {
            StageUIHelper.getInstance().showTipAlert("请输入服务器地址");
            return;
        }
        App.globalVal.httpHost = url;
        String faceIp = FieldFaceIP.getText().toString().trim();
        if (StringUtil.isNullOrEmpty(faceIp) || !Utils.validateIp(faceIp)) {
            StageUIHelper.getInstance().showTipAlert("请输入正确的IP!");
            return;
        }
        App.globalVal.faceIp = faceIp;
        SQLiteUtils.updateHttpUrl();
        StageUIHelper.getInstance().showTipAlert("修改成功", new Consumer<ButtonType>() {
            @Override
            public void accept(ButtonType buttonType) {
                SQLiteUtils.insertLog("修改成功，关闭设置");
            }
        });
    }


    @Override
    public void onDataChange() {
        reloadReader();
    }
}